import mysql from 'mysql';
import configDB from './db.config';


// sql 查询
let querys = async sql => {
  const connection = mysql.createConnection(configDB);
  connection.connect();
  let results = await new Promise((res, rej) => {
    connection.query(sql, (error, results) => {
      if (error) rej(error)
      res(results)
    })
  })
  connection.end();
  return results
}



// 添加
let insert = (tables, obj) => {
  // 解析obj对应的keys
  let keys = Object.keys(obj);
  // 解析对应的values 并且判断values类型
  let values = Object.keys(obj).map(item => typeof obj[item] === 'string' ? `'${obj[item]}'` : obj[item]);
  // 返回查询结果
  return querys(`insert into ${tables} (${keys.join(',')}) values (${values.join(',')})`)
}





export default {
  querys,
  insert
}